package com.power.bank.utils;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.iot20180120.AsyncClient;
import com.aliyun.sdk.service.iot20180120.models.*;
import com.github.tomakehurst.wiremock.common.Json;
import com.google.gson.Gson;
import com.power.bank.common.utils.StringUtils;
import com.power.bank.config.AliyunConfig;
import com.power.bank.enums.ApplyStatus;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class AliyunSendMessageUtils {


    @Autowired
    AliyunConfig aliyunConfig;


    /**
     * 添加设备
     *
     * @param nickName
     * @param productKey
     * @return
     */
    public String registerDrive(String nickName, String productKey) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliyunConfig.getAccessKeyId())
                .accessKeySecret(aliyunConfig.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(aliyunConfig.getEndpoint())
                )
                .build();


        RegisterDeviceRequest request = RegisterDeviceRequest.builder().iotInstanceId(aliyunConfig.getIotInstanceId()).nickname(nickName).
                productKey(productKey).build();


        CompletableFuture<RegisterDeviceResponse> response = client.registerDevice(request);
        String result = "";
        try {
            RegisterDeviceResponse resp = response.get();
            System.out.println("调用阿里云平台返回信息：" + new Gson().toJson(resp));
            if (resp.getBody().getData() != null) {
                result = resp.getBody().getData().getIotId();
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }


    /**
     * 批量添加设备
     *
     * @param nickName
     * @param productKey
     * @return
     */
    public boolean BatchRegisterDevice(List<String> nickName, String productKey) {
        ApplyStatus applyStatus = checkDriveName(nickName, productKey);

        if (applyStatus == ApplyStatus.CHECK_SUCCESS) {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(aliyunConfig.getAccessKeyId())
                    .accessKeySecret(aliyunConfig.getAccessKeySecret())
                    .build());

            AsyncClient client = AsyncClient.builder()
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride(aliyunConfig.getEndpoint())
                    )
                    .build();


            return true;
        } else {
            return false;
        }


    }


    /**
     * 检查添加设备
     *
     * @param nickName
     * @param productKey
     * @return
     */
    public ApplyStatus checkDriveName(List<String> nickName, String productKey) {

        ApplyStatus applyStatus = ApplyStatus.FAILED;
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliyunConfig.getAccessKeyId())
                .accessKeySecret(aliyunConfig.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(aliyunConfig.getEndpoint())
                )
                .build();


        BatchCheckDeviceNamesRequest request = BatchCheckDeviceNamesRequest.builder().deviceName(nickName).productKey(productKey).build();


        CompletableFuture<BatchCheckDeviceNamesResponse> response = client.batchCheckDeviceNames(request);
        String result = "";
        try {
            BatchCheckDeviceNamesResponse resp = response.get();


            System.out.println("调用阿里云平台返回checkDriveName信息：" + new Gson().toJson(resp));
            if (resp.getBody().getData() != null) {
               long applyId = resp.getBody().getData().getApplyId();
                applyStatus = batchRegisterDeviceStatus(applyId, productKey);
            }




        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return applyStatus;
    }


    /**
     * 检查添加设备
     *
     * @param applyId 请求申请id
     * @return
     */
    public ApplyStatus batchRegisterDeviceStatus(long applyId, String productKey) {

        ApplyStatus applyStatus = ApplyStatus.FAILED;
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliyunConfig.getAccessKeyId())
                .accessKeySecret(aliyunConfig.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(aliyunConfig.getEndpoint())
                )
                .build();


        QueryBatchRegisterDeviceStatusRequest request = QueryBatchRegisterDeviceStatusRequest.builder().applyId(applyId)
                .productKey(productKey).build();


        CompletableFuture<QueryBatchRegisterDeviceStatusResponse> response = client.queryBatchRegisterDeviceStatus(request);
        String result = "";
        try {
            QueryBatchRegisterDeviceStatusResponse resp = response.get();
            System.out.println("调用阿里云平台返回batchRegisterDeviceStatus信息：" + new Gson().toJson(resp));
            if (resp.getBody().getData() != null) {
                String status  = resp.getBody().getData().getStatus();
                applyStatus = ApplyStatus.build(status);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return applyStatus;
    }


}
